package com.syqc.base

import android.Manifest
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.viewbinding.ViewBinding
import com.amap.api.maps.AMap
import com.permissionx.guolindev.PermissionX
import com.syqc.comlib.utils.toast
import com.syqc.maps.utils.MapUtil
import com.syqc.monitor.R

/**
 *@Author Jasper
 *@Time   2020/8/1
 *@Desc   地图定位Fragment
 */
abstract class BaseMapLocationFragment<VB : ViewBinding>(inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB) :
    BaseMapFragment<VB>(
        inflater
    ), AMap.OnMyLocationChangeListener {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mMap?.setOnMyLocationChangeListener(this)
    }

    private var isShow = false
    fun getPermissions(isShow: Boolean = false) {
        this.isShow = isShow
        PermissionX.init(requireActivity()).permissions(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ).onForwardToSettings { scope, deniedList ->
            scope.showForwardToSettingsDialog(
                deniedList,
                getString(
                    R.string.desc_permissions_msg,
                    getString(R.string.app_name)
                ),
                getString(R.string.desc_com_sure),
                getString(R.string.desc_cancel)
            )
        }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    initGPS()
                } else {
                    showToast(R.string.toast_no_has_permission)
                }
            }
    }

    private var isFirst = true

    /**
     * 监听GPS
     */
    protected open fun initGPS() {
        val locationManager =
            requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (isFirst) {
                // 转到手机设置界面，用户设置GPS
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                // 设置完成后返回到原来的界面
                launcherLocation.launch(intent)
            } else {
                R.string.toast_open_location_info.toast(requireContext())
            }
        } else {
            MapUtil.setLocationStyle(mMap!!, isShow)
        }
    }


    private val launcherLocation = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        isFirst = false
        initGPS()
    }
}